<?php
namespace Api\Controller;
use Home\Model\MemberModel;
use Home\Model\MemberInfoModel;
use Common\Controller\ApiController;

class MemberController extends ApiController {
    
    function _initialize() {
        parent::_initialize();
        //验证 APP KEY
        $timestamp = I('request.timestamp');
        $token = I('request.token');
        parent::checkAppToken($token,$timestamp);
    }
    
    
    function weixin_api($code) {
        $app_id = C('API_WX_ID');
        $app_secret = C('API_WX_SECRET');
        $url = "https://api.weixin.qq.com/sns/jscode2session";
       
        /**
         * 3.小程序调用server获取token接口, 传入code, rawData, signature, encryptData.
         */
        $code = I("request.code", '', 'htmlspecialchars_decode');
        $rawData = I("request.rawData", '', 'htmlspecialchars_decode');
        $signature = I("request.signature", '', 'htmlspecialchars_decode');
        $encryptedData = I("request.encryptedData", '', 'htmlspecialchars_decode');
        $iv = I("request.iv", '', 'htmlspecialchars_decode');

        /**
         * 4.server调用微信提供的jsoncode2session接口获取openid, session_key, 调用失败应给予客户端反馈
         * , 微信侧返回错误则可判断为恶意请求, 可以不返回. 微信文档链接
         * 这是一个 HTTP 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。其中 session_key 是对用户数据进行加密签名的密钥。
         * 为了自身应用安全，session_key 不应该在网络上传输。
         * 接口地址："https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code"
         */
        $params = array(
            'appid' => $app_id,
            'secret' => $app_secret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        );
        $res = makeRequest($url, $params);

        if ($res['code'] !== 200 || !isset($res['result']) || !isset($res['result'])) { 
            $this->response($res,C('API_TYPE'));
        }
        $reqData = json_decode($res['result'], true);
        if (!isset($reqData['session_key'])) {
            $this->response(ret_message('requestTokenFailed'),C('API_TYPE'));
        }
        $sessionKey = $reqData['session_key'];


         /**
         * 5.server计算signature, 并与小程序传入的signature比较, 校验signature的合法性, 不匹配则返回signature不匹配的错误. 不匹配的场景可判断为恶意请求, 可以不返回.
         * 通过调用接口（如 wx.getUserInfo）获取敏感数据时，接口会同时返回 rawData、signature，其中 signature = sha1( rawData + session_key )
         *
         * 将 signature、rawData、以及用户登录态发送给开发者服务器，开发者在数据库中找到该用户对应的 session-key
         * ，使用相同的算法计算出签名 signature2 ，比对 signature 与 signature2 即可校验数据的可信度。
         */
        $signature2 = sha1($rawData . $sessionKey);

        if ($signature2 !== $signature) return ret_message("signNotMatch");
        
       
        /**
         *
         * 6.使用第4步返回的session_key解密encryptData, 将解得的信息与rawData中信息进行比较, 需要完全匹配,
         * 解得的信息中也包括openid, 也需要与第4步返回的openid匹配. 解密失败或不匹配应该返回客户相应错误.
         * （使用官方提供的方法即可）
         */
         vendor('Weixin.wxBizDataCrypt');
         
         
        $pc = new \Vendor\Weixin\wxBizDataCrypt($app_id, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode !== 0) {
            $this->response($errCode,C('API_TYPE'));
        }
     /**
         * 7.生成第三方3rd_session，用于第三方服务器和小程序之间做登录态校验。为了保证安全性，3rd_session应该满足：
         * a.长度足够长。建议有2^128种组合，即长度为16B
         * b.避免使用srand（当前时间）然后rand()的方法，而是采用操作系统提供的真正随机数机制，比如Linux下面读取/dev/urandom设备
         * c.设置一定有效时间，对于过期的3rd_session视为不合法
         *
         * 以 $session3rd 为key，sessionKey+openId为value，写入memcached
         */
        $data = json_decode($data, true);
        $session3rd = random(16);

         $data['session3rd'] = $session3rd;
         $data['openId'] = $reqData['openid'];
         
         cookie($session3rd, $data['openId'],604800);
         cookie($session3rd.'_seesion_key', $sessionKey,604800);

         $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 修改生日
     * @param int $member_id 会员ID
     * @param date $date 生日
     */
    function edit_birthday($member_id,$date) {
        $MemberInfoObj = new MemberInfoModel();
        $flag = $MemberInfoObj->where('member_id=' . $member_id)->setField('birthday', $date);
        $data['code'] = '200';
        $data['msg'] = '';
        $data['success'] = $flag;
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 修改性别
     * @param int $member_id 会员ID
     * @param date $date 生日
     */
    function edit_sex($member_id,$sex) {
        $MemberInfoObj = new MemberInfoModel();
        $flag = $MemberInfoObj->where('member_id=' . $member_id)->setField('sex', $sex);
        $data['code'] = '200';
        $data['msg'] = '';
        $data['success'] = $flag;
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 修改真实姓名
     * @param int $member_id 会员ID
     * @param date $realname 姓名
     */
    function edit_realname($member_id,$realname) {
        $MemberInfoObj = new MemberInfoModel();
        $flag = $MemberInfoObj->where('member_id=' . $member_id)->setField('realname', $realname);
        $data['code'] = '200';
        $data['msg'] = '';
        $data['success'] = $flag;
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * APP上传头像
     * @param int $member_id 会员ID
     */
    function upload_headpic($member_id) {
       //定义服务器存储路径和文件名
       $dir = 'Public/upload/headpic/180/';
       $filename = $member_id.".png";
       $receiveFile =  $_SERVER["DOCUMENT_ROOT"]."/".$dir.$filename; 
       $streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA']:'';
       if(empty($streamData)){ 
          $streamData = file_get_contents('php://input'); 
       }
       if($streamData!=''){ 
          $ret = file_put_contents($receiveFile, $streamData, true); 
          $MemberObj = new MemberModel();
          $flag = $MemberObj->where('member_id=' . $member_id)->setField('headpic', $dir . $filename);
       } else { 
          $ret = false; 
       }
       $data['code'] = '200';
       $data['msg'] = '';
       $data['success'] = (bool)$ret;
       $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 获取用户信息
     * @param int $member_id 会员ID
     */
    function login_info_index($member_id) {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberObj = new MemberModel();
        $result = $MemberObj->field('headpic,username,email,phone,point,money,level_id')->where(array('member_id'=>$member_id))->find();
        if(empty($result)) {
            $data['code'] = '500';
            $data['msg'] = '用户不存在';
        } else {
            $MemberLevelObj = new \Home\Model\MemberLevelModel();
            $result['level_name']= $MemberLevelObj->get_level_name($result['level_id']);//会员等级
            $data['data'] = $result;
        }
        $this->response($data,C('API_TYPE'));
    }
    
    //我的订单列表
    public function myorder($member_id) {
        $data['code'] = '200';
        $data['msg'] = '';
        $ModelObj = new \Fwadmin\Model\OrderModel();
        $conditions = array();//搜索条件
        $status_mark = I('get.status_mark',0);
        if(!empty($status_mark)) {
            $conditions['status_mark'] = $status_mark;
        }
        $k = I('get.k','');
        if(!empty($k)) {
            $conditions['k'] = $k;
        }
        $pagesize = I('get.pagesize',10);
        $results2 = $ModelObj->search_member($member_id,$conditions,'order_id desc',$pagesize);
        $lists = $results2['list'];
        foreach($lists as $k => $v) {
            $lists[$k]['status_str'] = $ModelObj->show_status_member($v['status'], $v['status_pay'], $v['status_delivery'],$v['pay_type']);//订单状态
            $lists[$k]['total_show'] = $v['total'] - $v['total_discount'];//显示价格
            $lists[$k]['pay_type_str'] = $ModelObj->get_pay_type($v['pay_type']);//支付方式
            $lists[$k]['goods'] = $ModelObj->show_goods_pic($v['order_id']);//订单图片数组
            $lists[$k]['time_create'] = date('Y-m-d',$lists[$k]['time_create']);//下单时间
        }
       
        $result['list'] = $lists;
        $result['total'] = $results2['count'];//总记录数
        $result['page_count'] = $results2['page_count'];
        $result['current_page'] = I('get.p',1);//当前第几页
       
        $data['data'] = $result;
                
        $this->response($data,C('API_TYPE'));
    }
    
    //订单详细页面
    public function orderinfo($member_id,$id) {
        $data['code'] = '200';
        $data['msg'] = '';
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $order = $OrderObj->where(array('member_id'=>$member_id))->find($id);
        //防止查看别人的订单
        if(empty($order)) {
            $data['code'] = '500';
            $data['msg'] = '订单不存在';
        }
        $order['pay_type_str'] = $OrderObj->get_pay_type($order['pay_type']);//支付方式
        $order['status_str'] = $OrderObj->show_status_member($order['status'], $order['status_pay'], $order['status_delivery'],$order['pay_type']);//订单状态
        $order['total_show'] = $order['total'] - $order['total_discount'];//显示价格
        $order['total_need_pay'] = $order['total'] - $order['total_discount'] - $order['total_pay'] - $order['total_pay_point'];//待支付金额
        $order['total_need_pay'] = round($order['total_need_pay'],2);
        $result['order'] = $order;
        
        //订单跟踪信息
        $result['record'] = $OrderObj->get_record($id);
        //订单购物车信息
        $result['goods'] = $OrderObj->get_goods($id);
        
        $data['data'] = $result;
                
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 修改密码
     * @param int $member_id 会员ID
     * @param string $old_password StrongMD5加密过的旧密码
     * @param string $new_password StrongMD5加密过的新密码
     */
    public function change_password($member_id,$old_password,$new_password) {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberObj = new MemberModel();
        $old_password = I('get.old_password');
        $new_password = I('get.new_password');
        //检测旧密码是否正确
        $is_right = $MemberObj->check_old_password($member_id, $old_password);
        if(!$is_right) {
            $data['code'] = '500';
            $data['msg'] = '旧密码错误！';
        } else {
            //执行修改密码操作
            $flag = $MemberObj->change_password($member_id,$new_password);
            if ($flag > 0) {
                $data['msg'] = '修改密码成功！';
            } else {
                $data['code'] = '500';
                $data['msg'] = '修改密码失败！';
            }
        }
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 获取会员基本信息
     * @param int $member_id 会员ID
     */
    public function get_info($member_id) {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberObj = new MemberModel();
        $MemberInfoObj = new MemberInfoModel();
        $member = $MemberObj->find($member_id);
        $memberinfo = $MemberInfoObj->find($member_id);
        $memberinfo['year'] = date('Y', strtotime($memberinfo['birthday']));
        $memberinfo['month'] = date('m', strtotime($memberinfo['birthday']));
        $memberinfo['day'] = date('d', strtotime($memberinfo['birthday']));
        if(empty($member)) {
            $data['code'] = '500';
            $data['msg'] = '会员不存在';
        } else {
            $result['headpic'] = $MemberObj->get_headpic($member_id);//会员头像
            $result['birthday'] = $memberinfo['birthday'];
            $result['username'] = $member['username'];
            $result['nickname'] = $member['nickname'];
            $result['realname'] = $memberinfo['realname'];
            $result['sex'] = $memberinfo['sex'];
            $data['data'] = $result;
        }
        $this->response($data,C('API_TYPE')); 
    }
    
    /**
     * 收货地址列表
     */
    public function address($member_id) {
        $MemberAddressObj = new \Home\Model\MemberAddressModel();
        $map['member_id'] = $member_id;
        $order = 'is_default desc,id desc';
        $result = $MemberAddressObj->where($map)->order($order)->select();
        $data['code'] = '200';
        $data['msg'] = '';
        $data['data'] = $result;
        $this->response($data,C('API_TYPE')); 
    }
    
     /**
     * 获取单个收货地址
     */
    public function address_get($member_id,$id) {
        $MemberAddressObj = new \Home\Model\MemberAddressModel();
        $map['member_id'] = $member_id;
        $map['id'] = $id;
        $result = $MemberAddressObj->where($map)->find($id);
        if(!empty($result)) {
            $data['code'] = '200';
            $data['msg'] = '';
            $data['data'] = $result;
        } else {
            $data['code'] = '500';
            $data['msg'] = '收货地址不存在';
            $data['data'] = '';
        }
        $this->response($data,C('API_TYPE')); 
    }
    
    /**
     * 新增收货地址
     * @param type $type
     */
    public function address_add() {
        $result['code'] = '200';
        $data['realname'] = trim(I('post.realname',''));
        $data['province'] = trim(I('post.province',''));
        $data['city'] = trim(I('post.city',''));
        $data['area'] = trim(I('post.area',''));
        $data['address'] = trim(I('post.address',''));
        //$data['zip'] = trim(I('post.zip',''));
        $data['phone'] = trim(I('post.phone',''));
        //$data['tel'] = trim(I('post.tel',''));
       // $data['email'] = trim(I('post.email',''));
        $data['is_default'] = I('post.is_default',0);
        $data['member_id'] = I('post.member_id',0);;
        if($data['realname'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请填写收件人';
        } elseif ($data['province'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请选择省份';
        } elseif ($data['city'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请选择城市';
        } elseif ($data['phone'] == '' ) {
            $result['code'] = '500';
            $result['msg'] = '请填写联系手机';
        } else {
            $MemberAddressObj = new \Home\Model\MemberAddressModel();
            $id = $MemberAddressObj->add($data);
            if($id > 0) {
                if($data['is_default'] == 1) {
                    $MemberAddressObj->set_default($data['member_id'], $id);
                }
                $result['data'] = 'success';
            } else {
                $result['code'] = '500';
                $result['msg'] = '新增收货地址出错！';
            }
        }
        $this->response($result,C('API_TYPE')); 
    }
    
    //修改收货地址
    //$type = ajax时为订单确认过程时使用
    public function address_edit() {
        $result['code'] = '200';
        $id = I('post.id',0);;
        $member_id = I('post.member_id',0);;
        $MemberAddressObj = new \Home\Model\MemberAddressModel();
        $model = $MemberAddressObj->get_address($member_id, $id);
        if(empty($model)) {
            $data['code'] = '500';
            $data['msg'] = '非法操作！';
        }
        $data['realname'] = trim(I('post.realname',''));
        $data['province'] = trim(I('post.province',''));
        $data['city'] = trim(I('post.city',''));
        $data['area'] = trim(I('post.area',''));
        $data['address'] = trim(I('post.address',''));
       // $data['zip'] = trim(I('post.zip',''));
        $data['phone'] = trim(I('post.phone',''));
       // $data['tel'] = trim(I('post.tel',''));
       // $data['email'] = trim(I('post.email',''));
        $data['is_default'] = I('post.is_default',0);
        $data['member_id'] = $member_id;
        $data['id'] = $id;
         if($data['realname'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请填写收件人';
        } elseif ($data['province'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请选择省份';
        } elseif ($data['city'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请选择城市';
        } elseif ($data['phone'] == '') {
            $result['code'] = '500';
            $result['msg'] = '请填写联系手机';
        } else {
            $flag = $MemberAddressObj->save($data);
            if($flag !== false) {
                if($data['is_default'] == 1) {
                    $MemberAddressObj->set_default($member_id, $id);
                }
                $result['data'] = 'success';
            } else {
                $result['code'] = '500';
                $result['msg'] = '新增收货地址出错！';
            }
        }
        $this->response($result,C('API_TYPE')); 
    }
    
    //删除收货地址AJAX操作
    public function address_del($member_id,$id) {
        $data['code'] = '200';
        $MemberAddressObj = new \Home\Model\MemberAddressModel();
        $flag = $MemberAddressObj->del_address($member_id, $id);
        if($flag > 0) {
             $data['data'] = 'success';
        } else {
            $data['code'] = '500';
            $data['msg'] = '新增收货地址出错！';
        }
        $this->response($data,C('API_TYPE')); 
    }
    
    /**
     * 设置默认地址
     * @param int $member_id 会员ID
     * @param int $id 地址ID
     */
    public function address_set_default($member_id,$id) {
        $data['code'] = '200';
        $MemberAddressObj = new \Home\Model\MemberAddressModel();
        $flag = $MemberAddressObj->set_default($member_id, $id);
        if($flag > 0) {
             $data['data'] = 'success';
        } else {
            $data['code'] = '500';
            $data['msg'] = '设置默认地址出错！';
        }
        $this->response($data,C('API_TYPE')); 
    }
    
    //我的收藏
    public function myfav($member_id) {
        $data['code'] = '200';
        $FavObj = new \Home\Model\MemberFavModel();
        $GoodsObj = new \Home\Model\GoodsModel();
        $GoodsItemObj = M('goods_item');
        $result = $FavObj->search_member($member_id,50);
        $list = $result['list'];
        foreach($list as $k => &$v) {
            $item = $GoodsItemObj->field('goods_sn,price,spec_array')->where(array('item_id'=>$v['item_id']))->find();
            if(!empty($item)) {
                $v['price_duibi'] = $v['price_before'] - $item['price'];
                $v['price'] = $item['price'];
                $v['goods_sn'] = $item['goods_sn'];
                $v['spec_array'] = $item['spec_array'];
            } else {
                unset($list[$k]);
            }
        }
        $list = array_values($list);
        $data['data'] = $list;
        $this->response($data,C('API_TYPE')); 
    }
    
    //删除收藏
    public function myfav_del($member_id,$id) {
        $data['code'] = '200';
        $FavObj = new \Home\Model\MemberFavModel();
        $flag = $FavObj->del_fav($id,$member_id);
        if($flag > 0) {
            $data['msg'] = '删除成功！';
        } else {
            $data['code'] = '500';
            $data['msg'] = '删除失败！';
        }
         $this->response($data,C('API_TYPE')); 
    }
}